//
//  YSComtBottomView.m
//  Yueshi
//
//  Created by Northwan on 15/8/7.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSComtBottomView.h"
@interface YSComtBottomView()<UITextViewDelegate>
@end
@implementation YSComtBottomView


-(void)awakeFromNib{
    self.commentTextView.delegate = self;
    [self.publishBtn setEnabled:NO];
}

+(instancetype)bottomView{
    return [[[NSBundle mainBundle]loadNibNamed:@"YSComtBottomView" owner:nil options:nil]lastObject];
}

- (IBAction)publish:(id)sender {
    if(ISBLANK(self.commentTextView.text)){
        ShowTips(@"请输入内容");
        return;
    }
    if ([self.delegate respondsToSelector:@selector(publish:)]) {
        [_delegate publish:self.commentTextView.text];
    }
}

#pragma mark -
#pragma mark TextFieldDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if(ISBLANK(text.trim)){
        if(textView.text.trim.length <= 1){
            [self.publishBtn setEnabled:NO];
        }else{
            [self.publishBtn setEnabled:YES];
        }
    }else{
        [self.publishBtn setEnabled:YES];
    }
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [textView flashScrollIndicators];   // 闪动滚动条
    
    static CGFloat maxHeight = 100.0f;
    CGRect frame = textView.frame;
    CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
    CGSize size = [textView sizeThatFits:constraintSize];
    if (size.height >= maxHeight){
        size.height = maxHeight;
        textView.scrollEnabled = YES;   // 允许滚动
    }else{
        textView.scrollEnabled = NO;    // 不允许滚动，当textview的大小足以容纳它的text的时候，需要设置scrollEnabed为NO，否则会出现光标乱滚动的情况
    }
    
    //计算便宜的高度就是需要移动的Y值：新的高度+上下间距 - 原来的高度 = 需要偏移的Y值
    CGFloat offsetY = size.height + 17 - self.height;
    
    textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
    
    self.height = size.height + 17;
    
    if ([_delegate respondsToSelector:@selector(textViewTextDidChange:)]){
        [_delegate textViewTextDidChange:offsetY];
    }
}

@end
